package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    @Autowired
    private ApUserMapper apUserMapper;


    @Override
    public ResponseResult login(LoginDto dto) {

        if(dto.getEquipmentId()==null && (dto.getPhone()==null||dto.getPassword()==null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        List<ApUser> apUsers = apUserMapper.selectList(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if(apUsers.size()>0){
            ApUser apUser = apUsers.get(0);
            String pswd = DigestUtils.md5DigestAsHex((dto.getPassword()+apUser.getSalt()).getBytes());
            if(apUser.getPassword().equals(pswd)){
                Map<String, Object> map = new HashMap<>();
                apUser.setPassword("");
                apUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user", apUser);
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else{
            //根据设备生成token  0
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }

    @Override
    public ApUser findById(Integer id) {
        return this.getById(id);
    }
}
